package org.dromara.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.dromara.admin.domain.ProductCategory;
import org.dromara.admin.domain.ProductGroup;
import org.dromara.admin.domain.vo.EmployeeVo;
import org.dromara.admin.service.IEmployeeService;
import org.dromara.admin.service.IProductCategoryService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.dromara.admin.domain.bo.ProductBo;
import org.dromara.admin.domain.vo.ProductVo;
import org.dromara.admin.domain.Product;
import org.dromara.admin.mapper.ProductMapper;
import org.dromara.admin.service.IProductService;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 产品信息Service业务层处理
 *
 * @author Lion Li
 * @date 2025-10-10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ProductServiceImpl implements IProductService {

    private final ProductMapper baseMapper;
    private final IEmployeeService employeeService;

    /**
     * 查询产品信息
     *
     * @param id 主键
     * @return 产品信息
     */
    @Override
    public ProductVo queryById(Long id) {
        ProductVo productVo = baseMapper.selectVoById(id);
        if (BeanUtil.isEmpty(productVo)) {
            throw new ServiceException("产品编号：" + id + "信息不存在！");
        }
        return productVo;
    }

    /**
     * 分页查询产品信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 产品信息分页列表
     */
    @Override
    public TableDataInfo<ProductVo> queryPageList(ProductBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Product> lqw = buildQueryWrapper(bo);
        Page<ProductVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 分页查询当前登录用户的公司产品信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 产品信息分页列表
     */
    @Override
    public TableDataInfo<ProductVo> queryPageMyList(ProductBo bo, PageQuery pageQuery) {
        EmployeeVo employeeVo = employeeService.queryById(bo.getCompanyId());

        bo.setCompanyId(employeeVo.getCompanyId()); // 重新赋值主体id
        MPJLambdaWrapper<Product> mpjWrapper = getProductInfoByJoinTable(bo);
        Page<ProductVo> result = baseMapper.selectJoinPage(pageQuery.build(), ProductVo.class, mpjWrapper);
        return TableDataInfo.build(result);
    }

    /**
     * 联表查询ProductCategory、 Product
     */
    private static MPJLambdaWrapper<Product> getProductInfoByJoinTable(ProductBo bo) {
        // 使用MPJBaseMapper进行联表查询ProductCategory、ProductGroup、 Product
        return new MPJLambdaWrapper<Product>()
            .selectAll(Product.class)
            .selectAssociation(ProductCategory.class, ProductVo::getProductCategoryInfo)
            .selectAssociation(ProductGroup.class, ProductVo::getProductGroupInfo)
            .leftJoin(ProductCategory.class, ProductCategory::getId, Product::getCategoryId)
            .leftJoin(ProductGroup.class, ProductGroup::getId, Product::getGroupId)
            .orderByDesc(Product::getSort).orderByDesc(Product::getId)
            .eq(bo.getCompanyId() != null, Product::getCompanyId, bo.getCompanyId())
            .eq(bo.getCreatorId() != null, Product::getCreatorId, bo.getCreatorId())
            .eq(bo.getCategoryId() != null, Product::getCategoryId, bo.getCategoryId())
            .eq(bo.getGroupId() != null, Product::getGroupId, bo.getGroupId())
            .like(StringUtils.isNotBlank(bo.getName()), Product::getName, bo.getName())
            .eq(bo.getUnitPrice() != null, Product::getUnitPrice, bo.getUnitPrice())
            .eq(bo.getPurchasePrice() != null, Product::getPurchasePrice, bo.getPurchasePrice())
            .eq(StringUtils.isNotBlank(bo.getUnit()), Product::getUnit, bo.getUnit())
            .like(StringUtils.isNotBlank(bo.getSpec()), Product::getSpec, bo.getSpec())
            .eq(bo.getStock() != null, Product::getStock, bo.getStock());
    }

    /**
     * 查询符合条件的产品信息列表
     *
     * @param bo 查询条件
     * @return 产品信息列表
     */
    @Override
    public List<ProductVo> queryList(ProductBo bo) {
        LambdaQueryWrapper<Product> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Product> buildQueryWrapper(ProductBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Product> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(Product::getSort).orderByDesc(Product::getId);
        lqw.eq(bo.getCompanyId() != null, Product::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getCreatorId() != null, Product::getCreatorId, bo.getCreatorId());
        lqw.eq(bo.getCategoryId() != null, Product::getCategoryId, bo.getCategoryId());
        lqw.eq(bo.getGroupId() != null, Product::getGroupId, bo.getGroupId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), Product::getName, bo.getName());
        lqw.eq(bo.getUnitPrice() != null, Product::getUnitPrice, bo.getUnitPrice());
        lqw.eq(bo.getPurchasePrice() != null, Product::getPurchasePrice, bo.getPurchasePrice());
        lqw.eq(StringUtils.isNotBlank(bo.getUnit()), Product::getUnit, bo.getUnit());
        lqw.like(StringUtils.isNotBlank(bo.getSpec()), Product::getSpec, bo.getSpec());
        lqw.eq(bo.getStock() != null, Product::getStock, bo.getStock());
        return lqw;
    }

    /**
     * 新增产品信息
     *
     * @param bo 产品信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ProductBo bo) {
        Product add = MapstructUtils.convert(bo, Product.class);
        // 查询用户信息
        EmployeeVo employeeVo = employeeService.queryById(bo.getCreatorId());
        add.setCompanyId(employeeVo.getCompanyId());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改产品信息
     *
     * @param bo 产品信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ProductBo bo) {
        Product update = MapstructUtils.convert(bo, Product.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Product entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除产品信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }


    /**
     * 获取存在产品信息的分类ID集合
     *
     * @param categoryIds 分类ID集合
     * @return 存在产品的分类ID列表
     */
    @Override
    public List<Long> getCategoryIdsWithProducts(Collection<Long> categoryIds) {
        if (CollUtil.isEmpty(categoryIds)) {
            return Collections.emptyList();
        }

        return baseMapper.selectList(
                new LambdaQueryWrapper<Product>()
                    .in(Product::getCategoryId, categoryIds)
                    .select(Product::getCategoryId)
            ).stream()
            .map(Product::getCategoryId)
            .distinct()
            .collect(Collectors.toList());
    }

    /**
     * 获取存在产品信息的分组ID集合
     *
     * @param groupIds 分组ID集合
     * @return 存在产品的分组ID列表
     */
    @Override
    public List<Long> getGroupIdsWithProducts(Collection<Long> groupIds) {
        if (CollUtil.isEmpty(groupIds)) {
            return Collections.emptyList();
        }
        return baseMapper.selectList(
                new LambdaQueryWrapper<Product>()
                    .in(Product::getGroupId, groupIds)
                    .select(Product::getGroupId)
            ).stream()
            .map(Product::getGroupId)
            .distinct()
            .collect(Collectors.toList());
    }

    /**
     * 根据主体公司id查询所属的产品总数
     *
     * @param companyId 主体公司id
     * @return 产品总数
     */
    @Override
    public Long queryProductTotalByCompanyId(Long companyId) {
        return baseMapper.selectCount(
            new LambdaQueryWrapper<Product>()
                .eq(Product::getCompanyId, companyId)
        );
    }

    /**
     * 批量保存产品信息
     *
     * @param list   产品信息列表
     * @param userId 操作用户ID
     * @return 是否保存成功
     */
    @Override
    public Boolean saveBatch(List<Product> list, Long userId) {
        EmployeeVo employeeVo = employeeService.queryById(userId);
        // 填充公司ID以及创建人ID
        list.forEach(product -> {
            product.setCompanyId(employeeVo.getCompanyId());
            product.setCreatorId(userId);
        });
        boolean result = baseMapper.insertBatch(list);
        if (!result) {
            throw new ServiceException("导入产品时批量保存产品信息失败！");
        }
        return Boolean.TRUE;
    }
}
